<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\CommonController;

class UserController extends CommonController {
    /*public function __construct(){
        parent::__construct();
        if(!I('session.admin_uid')){
            $this->error('请登录后访问',U('Public/login'));
        }
    }*/



    /**
     *  注册用户列表
     * @return void
     */
    public function index(){
        $userName = I('get.username', '');
        $mobile = I('get.mobile', '');

        $map = array();
        if($userName) {
            $map['realname'] = array("like","%{$userName}%");
        }
        if($mobile) {
            $map['mobile'] = $mobile;
        }

        $userModel = M('User');
        $total = $userModel
                ->where($map)
                ->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $userList = $userModel->alias('u')
                ->field('*,ui.status userstatus,jb.name jobsname,ch.name channelname,ui.realnamepy realnamepy')
                ->join('__USER_INFO__ ui ON u.uid = ui.uid')
                ->join('__JOB__ jb on jb.jid=ui.userjobs','left')
                ->join('__CHANNEL__ ch on ch.chid=ui.userchannel','left')
                ->where($map)
                ->page($_GET['p'].',25')
                ->order('u.uid DESC')
                ->select();       
        $userGroupList=M('User_group')->where(array('status'=>1))->order('sort ASC')->select();

        $channellist=M('channel')->where(array('status'=>1))->order('sort ASC')->select();
        $joblist=M('job')->where(array('status'=>1))->order('sort ASC')->select();
        $this->assign('channellist', $channellist);
        $this->assign('joblist', $joblist);
        $this->assign('showPage', $show);
        $this->assign('userGroupList', $userGroupList);
        $this->assign('userList', $userList);
        $this->display();
    }

    /**
     *  用户注册设置
     * @return void
     */
    public function reg_setup(){
        if(IS_POST){
            $regType['value']=I('post.reg_type');
            $saveresult=M('system_config')->where(array('config'=>'RegType'))->save($regType);

        }
        $sysconfig=M('system_config')->getByConfig('RegType');
        if($sysconfig['value']==1){
            $client_type=I('get.clientType','IOS');
            if($client_type){
                $list=M('reg_config')->where(array('client_type'=>$client_type))->select();
                $this->assign(array('list'=>$list,'client_type'=>$client_type));
            }
        }

        $this->assign('regType',$sysconfig['value']);
        $this->display();
        if(isset($saveresult) &&  $saveresult){
            echo ('<script>$("#infostext").find("strong").html("已经成功设置！").end().addClass("in");setTimeout(function(){$("#infostext").removeClass("in").find("strong").empty;},2000);</script>');
        }
    }

    public function newVersion(){
        if(IS_POST){
            if(I("post.version")){
                $res=M('reg_config')->add(I("post."));
                if($res){
                    $this->success('添加成功！',U('reg_setup'));
                }else{
                    $this->error('添加失败！');
                }
            }else{
                $this->error('请填写版本号！');
            }
        }
    }

    public function ajax_set_reg($id='',$state=''){
        if($id && $state!=""){
           $res= M('reg_config')->save(array('id'=>$id,'can_reg'=>$state));
           if($res){
               echo 1;
           }else{
               echo 0;
           }
        }else{
            echo 0;
        }
    }

    public function update_reg_config(){
        if(IS_POST){
            $reg_config=I('post.version');
            $key=array_keys(I('post.version'));
            $key=$key[0];
            foreach($reg_config[$key] as $k=>$val){
                M('reg_config')->save(array('id'=>$k,'can_reg'=>$val));
            }
            $this->success('设置成功！',U('reg_setup'));
        }
    }

    public function ajax_del_version($id=''){
        if($id){
            $res=M('reg_config')->delete($id);
            if($res){
               echo 1;
            }else{
              echo 0;
            }
        }else{
            echo 0;
        }
    }
    public function ajaxdeluer($uid=''){
        $user_info=M('User_info');
        $user=M('User');
        if($uid){

            $user_info->startTrans();
            if($user_info->where(array('uid'=>$uid))->delete() && $user->delete($uid)){
                $user_info->commit();
                $this->ajaxReturn(1);
            }else{
                $user_info->rollback();
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }

    public function ajaxdeluerall($uid=''){
        $user_info=M('User_info');
        $user=M('User');
        if($uid){
            $user_info->startTrans();
            if($user_info->where("uid in ($uid)")->delete() && $user->where("uid in ($uid)")->delete()){
                $user_info->commit();
                $this->ajaxReturn(1);
            }else{
                $user_info->rollback();
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }

    public function ajaxgetuserinfo($uid=''){
        $user=M('User');
        if($uid){
            $userinfo=$user->alias('u')->join('__USER_INFO__ on __USER_INFO__.uid=u.uid')->where('u.uid='.$uid)->find();
            if($userinfo){
                $this->ajaxReturn($userinfo);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }
    public function editUserAction(){

        if(IS_POST){
            $user=D('user');
            $user_info=D('UserInfo'); 

            if(!$_POST['username']) {
                unset($_POST['username']);
            } 
            
            if($user_info->create()){
                $user_info->save();
                if($_POST['username'] && $user->create()) {
                     $user->save();
                } else {
                    $this->error($user->getError());
                }          
               
                $this->success('修改成功',U('index'));
            }else{
                if($user->getError()){
                    $this->error($user->getError());
                }else{
                     $this->error($user_info->getError());
                }
            }
        }
    }

    public function addUserAction(){

         if(IS_POST){
            $user=D('user');
            $user_info=D('UserInfo'); 

            if(!$_POST['username']) {
                $_POST['username'] = 'm' . time();
            }
 
            if($user_info->create() && $dataGet=$user->create()){
                $res=$user->add();
                if($res) {
                    $user_info->uid = $res;
                    $user_info->add();
                    $this->success('添加成功');
                    exit;
                } else {
                    $this->error('添加失败');
                }
            }else{
                if($user->getError()){
                    $this->error($user->getError());
                }else{
                     $this->error($user_info->getError());
                }
            }
        }

        if(!D('User')->create(I('post.'),4))
            $this->error(D('User')->getError());
        }

    public function ajaxcheckusername(){
        $_POST['username']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('User')->create()){
            echo '{
            "info":" ",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('User')->getError().'",
                "status":"n"
            }';
         }
        
    }
    public function ajaxMobileCheck(){
        $_POST['mobile']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('UserInfo')->create()){
            echo '{
            "info":" ",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('UserInfo')->getError().'",
                "status":"n"
            }';
         }
        
    }
    
    
    public function ajaxEmailCheck(){
        $_POST['email']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('UserInfo')->create()){
            echo '{
            "info":" ",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('UserInfo')->getError().'",
                "status":"n"
            }';
         }
        
    }

    function authTree($authlist=""){
        $authlist=explode(",",$authlist);
        $system_channel_model=M('SystemChannel');
        $top_auth_list=$system_channel_model->where(array("spid"=>0,"ishide"=>1))->select();
        $arr['id']=0;
        $arr['item']=array();

        foreach($top_auth_list as $k=>$v){
            $arr['item'][]=array('id'=>"T_".$v['scid'],'child'=>'1','text'=>$v['channelname'],'item'=>array());
            $seconde_auth_list=$system_channel_model->where(array("spid"=>$v['scid'],"ishide"=>1))->select();
            foreach($seconde_auth_list as $kk=>$vv){
                $arr['item'][$k]['item'][$kk]=array('id'=>$vv['scid'],'text'=>$vv['channelname']);
                if(in_array($vv['scid'],$authlist)){
                    $arr['item'][$k]['item'][$kk]['checked']="1";
                }
            }
        }
        $this->ajaxReturn($arr);
    }

    function ajaxSetUserAuth(){
       $idList=I("get.idList");
        $regx='/^\d+$/';
        foreach(explode(",",$idList) as $v){
            preg_match($regx,$v,$a);
            if(count($a)>=1){
                $arr[]=$v;
            }
        }

        $idList=implode(",",$arr);

        $a=M('UserInfo')->save(array(
            'userauth'=>$idList,
            'uid'=>I("get.uid")
        ));
        $this->ajaxReturn($a);
    }


    function formatPinyinName(){
        ini_set('max_execution_time','0');
    	$user=M('UserInfo')->where('realnamepy=""')->select();
    	foreach($user as $v){
    		M('userInfo')->where(array('uid'=>$v['uid']))->save(array('realnamepy'=>zh2py($v['realname'])));
            echo M()->_sql().'<br>';
    	}
        
    }

    function formatPw(){
        $user=M('User')
        ->alias('u')
        ->join("__USER_INFO__ ui ON u.uid=ui.uid","left")
        ->select();
        foreach($user as $v){
                M('user')->where(array('uid'=>$v['uid']))->save(array('password'=>md5('whtvjw'.$v['mobile'])));
        }
    }

}